from functools import wraps
from flask import session, request

from restful.model.query import QueryOneInstance
from restful.model.tables import User, Role, Blog
from restful.response import ResponseUnauthorized, ResponseForbidden, ResponseBadRequest, ResponseNotFound

def params_required(params: dict):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            for key, expected_type in params.items():
                value = request.args.get(key)  # 从 URL 参数获取
                if value is None:
                    return ResponseBadRequest(msg=f"缺少参数 {key}")
                try:
                    if expected_type == 'str':
                        value = str(value)
                    elif expected_type == 'int':
                        value = int(value)
                    elif expected_type == 'float':
                        value = float(value)
                    elif expected_type == 'bool':
                        value = str(value).lower() in ['true', '1', 'yes']
                    else:
                        return ResponseBadRequest(msg=f"不支持的类型 {expected_type}")
                except (ValueError, TypeError):
                    return ResponseBadRequest(msg=f"参数 {key} 类型错误")
                kwargs[key] = value
            return f(*args, **kwargs)
        return decorated_function
    return decorator




def uid_required_target_user_generate(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 从URL参数中获取uid
        uid = kwargs.pop('uid', None)
        if uid is None:
            return ResponseBadRequest("缺少参数 uid")

        try:
            uid = int(uid)
        except ValueError:
            return ResponseBadRequest("参数 uid 应为整数")

        user = QueryOneInstance(User, {'id': uid})
        if not user:
            return ResponseNotFound("用户不存在")

        kwargs['target_user'] = user
        return f(*args, **kwargs)
    return decorated_function

def pid_required_target_post_generate(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 从URL参数中获取pid
        pid = kwargs.pop('pid', None)
        if pid is None:
            return ResponseBadRequest("缺少参数 pid")

        try:
            pid = int(pid)
        except ValueError:
            return ResponseBadRequest("参数 pid 应为整数")

        blog = QueryOneInstance(Blog, {'id': pid})
        if not blog:
            return ResponseNotFound("帖子不存在")

        kwargs['target_post'] = blog
        return f(*args, **kwargs)
    return decorated_function

def login_required_current_user_generate(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'uid' not in session:
            return ResponseUnauthorized("请先登录")

        user = QueryOneInstance(User, {'id': session['uid']})
        if not user:
            return ResponseUnauthorized("用户信息无效，请重新登录")

        kwargs['current_user'] = user
        return f(*args, **kwargs)
    return decorated_function


def admin_required_current_admin_generate(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'uid' not in session:
            return ResponseUnauthorized("请先登录")

        user = QueryOneInstance(User, {'id': session['uid']})

        if not user:
            return ResponseUnauthorized("用户信息无效，请重新登录")

        if not session['admin'] :
            return ResponseForbidden("需要管理员权限")

        role = QueryOneInstance(Role, {'uid': user.id})

        if not role or not role.admin:
            return ResponseForbidden("管理员权限无效")

        kwargs['current_admin'] = user
        return f(*args, **kwargs)
    return decorated_function

def add_session(uid):
    session['uid'] = uid

def del_session():
    session.clear()